import requests
import json
from datetime import datetime
import time

# OKX API的公共URL
base_url = "https://www.okx.com"

# 获取资金费率
def get_funding_rate_okx(all_token):
    endpoint = "/api/v5/public/funding-rate"
    result=[]
    for symbol in all_token:
        parts = symbol.rsplit('-', 1)
        instId = parts[0]  # "BTC-USDT-SWAP"
        try_time=5
        while(try_time):
            try:
                params = {
                    'instId': instId
                }
                response = requests.get(base_url + endpoint, params=params)
                data = response.json()["data"]
                timestamp = datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
                result.append({"time":timestamp,"trading_pair":symbol,"platform":"okx","funding_rate":float(data[0]["fundingRate"])*100})
                time.sleep(0.5)
                break
            except Exception as e:
                print(str(symbol)+"   okx 获取数据失败 重新获取 剩余尝试次数 "+str(try_time))
                try_time=try_time-1
    return result